package com.briup.estore.userAPI.web.filter;

import com.briup.estore.common.util.DateUtil;
import com.briup.estore.common.util.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author adam
 * @date 2022/1/13
 */
@Component
public class UserFilter implements Filter {
    @Autowired
    RedisCache redisCache;
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        Object user = httpServletRequest.getSession().getAttribute("user");
        if (user == null) {
            httpServletRequest.setAttribute("msg", "还未登录请先登录");
            httpServletRequest.getRequestDispatcher("toLogin").forward(httpServletRequest, httpServletResponse);
        } else {
            String nowDate = DateUtil.getNowDate();
            Object o=redisCache.getCacheObject(nowDate+":pv");
            Integer pv= Objects.isNull(o)?0: (int) o;
            redisCache.setCacheObject("pv",++pv);
            chain.doFilter(request, response);
        }

    }
}
